package utils.compiler;


import utils.io.FileUtils;

import javax.tools.*;
import java.io.File;
import java.io.IOException;

public class StringifyJavaClassCompiler {

   /* public static void compile(String stringifyJavaClass, File classFile) {
        FileUtils.copy(stringifyJavaClass,classFile);
        JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager standardJavaFileManager = javaCompiler.getStandardFileManager(null,null,null);
        Iterable javaFileObjects = standardJavaFileManager.getJavaFileObjects(classFile);
        JavaCompiler.CompilationTask task = javaCompiler.getTask(null,standardJavaFileManager,null,null,null,javaFileObjects);
        task.call();
        try {
            standardJavaFileManager.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
*/
    public static void compile(String stringifyJavaClass, File classFile) {
        FileUtils.copy(stringifyJavaClass,classFile);

        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

        JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager standardJavaFileManager = javaCompiler.getStandardFileManager(null,null,null);
        Iterable javaFileObjects = standardJavaFileManager.getJavaFileObjects(classFile);
        JavaCompiler.CompilationTask task = javaCompiler.getTask(null,standardJavaFileManager,diagnostics,null,null,javaFileObjects);
        task.call();
        for (Diagnostic<?> diag : diagnostics.getDiagnostics()){
            System.err.format("---error on line%d in %s",diag.getLineNumber(),diag);
        }
        try {
            standardJavaFileManager.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
